package sort;

import java.util.Arrays;

/**
 * 选择排序
 * 每次循环找出最小的数放到数组前面
 */
public class Selection {

    public static void main(String[] args) {   //时间复杂度：O(n^2)；适用场景：待排序个数较少
        Integer[] arr = {9,1,4,5,7,2,3,6};
        sort(arr);
        System.out.println(Arrays.toString(arr));
    }

    public static void sort(Comparable[] a){
        for(int i=0;i<a.length-1;i++){
            int minIndex = i;
            for(int j=i+1;j<a.length;j++){
                if(greater(a[minIndex],a[j])){
                    minIndex = j;
                }
            }
            exch(a,minIndex,i);
        }
    }

    public static boolean greater(Comparable v,Comparable w){
        return v.compareTo(w)>0;  //v>=w，返回true；v<w返回false
    }

    public static void exch(Comparable[] a,int i,int j){
        Comparable temp;
        temp = a[i];
        a[i] = a[j];
        a[j] = temp;
    }
}
